/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.upload;

import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.transaction.ReimburseUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.transaction.ReimburseUploadResponse;
import com.wttech.dzzf.process.constant.UserConstants;
import com.wttech.dzzf.process.dao.ReimburseInfosDao;
import com.wttech.dzzf.process.service.user.UserDetailInfosCreatorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 退款信息上传服务实现
 *
 * @author MaShibo
 * @date 2017/11/13.
 */
@Service
public class ReimburseInfosUploadService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReimburseInfosUploadService.class);

    @Resource
    private ReimburseInfosDao reimburseInfosDao;

    @Resource
    private RechargeInfosUploadService rechargeInfosUploadService;

    @Resource
    private UserDetailInfosCreatorService userDetailInfosCreatorService;

    @Resource
    private ThreadPoolTaskExecutor executor;

    private void process() {
        List<ReimburseUploadRequest> reimburses = reimburseInfosDao.queryReimburseUploadInfos();
        int total = reimburses.size();
        LOGGER.info("共{}条数据待处理", total);
        List<Future<Void>> futures = new ArrayList<>(total);
        reimburses.forEach(reimburse -> futures.add(executor.submit(() -> {
            processSingleReimburse(reimburse);
            return null;
        })));
        userDetailInfosCreatorService.getFutureResult(futures);
        LOGGER.info("处理完毕");
        executor.shutdown();
    }

    private void processSingleReimburse(ReimburseUploadRequest reimburse) {
        try {
            String cardId = reimburse.getCardId();
            rechargeInfosUploadService.processUserAboutInfo(cardId);
            ReimburseUploadResponse reimburseRsp = ETCCommHelper.upload(reimburse.getFileName(UserConstants.DEFAULT_PROVINCE_CODE), reimburse, ReimburseUploadResponse.class);
            LOGGER.info("退款信息上传响应{}", reimburseRsp.getInfo());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        ReimburseInfosUploadService service = context.getBean(ReimburseInfosUploadService.class);
        service.process();
    }
}
